"""ATM接口层"""

from lib import common
from db import db_handler

logger = common.get_logger('atm')


def check_balance_interface(username):
    """返回用户余额信息"""
    userdata = db_handler.select(username)
    balance = userdata.get('balance')
    result = f'用户[{username}]的余额是[{balance:.2f}]'
    logger.debug(result)
    return result


def withdraw_interface(username, withdraw_deposit):
    """提现功能接口

    提现成功，返回True和成功提示信息
    提现失败，返回False和失败提示信息
    """
    userdata = db_handler.select(username)
    balance = userdata.get('balance')
    if withdraw_deposit > balance:
        prompt_msg = f'用户[{username}]余额不足，提现失败。'
        logger.debug(prompt_msg)
        return False, prompt_msg
    userdata['balance'] -= withdraw_deposit
    prompt_msg = f'用户[{username}]提现[{withdraw_deposit:.2f}]成功。'
    userdata['flow'].append(prompt_msg)
    logger.info(prompt_msg)
    db_handler.save(userdata)
    return True, prompt_msg


def repay_interface(username, repayment):
    """还款功能接口"""
    userdata = db_handler.select(username)
    userdata['balance'] += repayment
    prompt_msg = f'用户[{username}]还款[{repayment:.2f}]成功。'
    userdata['flow'].append(prompt_msg)
    logger.info(prompt_msg)
    db_handler.save(userdata)
    return prompt_msg


def transfer_interface(username, to_username, money):
    """
    转账功能接口

    转账成功，返回True和成功提示信息
    转账失败，返回False和失败提示信息
    """
    to_userdata = db_handler.select(to_username)
    if not to_userdata:
        prompt_msg = f'用户[{to_username}]不存在!'
        logger.debug(prompt_msg)
        return False, prompt_msg
    userdata = db_handler.select(username)
    user_balance = userdata.get('balance')
    if money > user_balance:
        prompt_msg = f'账户余额不足！'
        logger.debug(prompt_msg)
        return False, prompt_msg
    userdata['balance'] -= money
    to_userdata['balance'] += money
    prompt_msg = f'用户[{username}]给用户[{to_username}]转账[{money}]成功。'
    logger.info(prompt_msg)
    userdata['flow'].append(prompt_msg)
    to_userdata['flow'].append(prompt_msg)
    db_handler.save(userdata)
    db_handler.save(to_userdata)
    return True, prompt_msg


def check_flow_interface(username):
    """查看流水功能接口"""
    userdata = db_handler.select(username)
    flow = userdata.get('flow')
    return flow
